package controllers

import (
	"accounting-software/models"
	"accounting-software/services"
	"net/http"
	"unicode/utf8"

	"github.com/gin-gonic/gin"
)

// 定义UserController结构体，返回userService
type UserController struct {
	userService *services.UserService
}

// 定义实例化UserController的方法
func NewUserController(userService *services.UserService) *UserController {
	return &UserController{userService: userService}
}

// 添加用户

func (uc *UserController) AddUser(c *gin.Context) {
	var user models.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 检查用户名是否可用
	isAvailable, err := uc.userService.IsUsernameAvailable(user.Name)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
		return
	}
	if !isAvailable {
		c.JSON(http.StatusConflict, gin.H{"error": "Username already exists"})
		return
	}
	// 校验密码长度
	if utf8.RuneCountInString(user.Password) < 8 {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "密码不能小于8位!"})
		return
	}

	if _, err := uc.userService.AddUser(user.Name, user.Password); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "Add user Successful!"})
}

// 用户登录
func (uc *UserController) Login(c *gin.Context) {
	name := c.Query("name")
	password := c.Query("password")
	token, err := uc.userService.Login(name, password)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"token": token})
}
